# coding:utf-8

from rest_framework.views import set_rollback
from rest_framework.response import Response
from rest_framework import exceptions
from django.http import Http404
from utils import logs


def exception_handler(exc, context):
    """
    错误code添加
    """
    data = dict()
    if isinstance(exc, Http404):
        exc = Http404()
        data["code"] = "404"

    if isinstance(exc, exceptions.APIException):
        headers = {}
        data["msg"] = exc.detail
        if "code" not in data:
            logs.error("接口错误: {}, Content: {}".format(exc, context))
            data["code"] = 500

        set_rollback()
        return Response(data, status=200, headers=headers)

    return None


def custom_exception_handler(exc, context):
    """
    异常捕获
    :param exc:
    :param context:
    :return: 修改状态码和返回code, request_id
    """
    response = exception_handler(exc, context)

    if response is not None:
        return response
    else:
        logs.error("接口错误: {}, Content: {}".format(exc, context))
        data = dict(
            code=500,
            msg="系统异常，请重试，或联系开发人员",
        )
    return Response(data, status=200)
